package com.aquarius.chapter2;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CopyOnWriteArrayListDemo {

	// 两个线程一个线程foreach一个线程修改list的值
	public static void main(String[] args) {
		new CopyOnWriteArrayListDemo().run();
		test();
	}

	class ReadTask implements Runnable {

		CopyOnWriteArrayList<String> list;

		public ReadTask(CopyOnWriteArrayList<String> list) {
			this.list = list;
		}

		@Override
		public void run() {
			for (String string : list) {
				System.out.println(string);
			}
		}
	}

	class WriteTask implements Runnable {

		CopyOnWriteArrayList<String> list;
		int index;

		public WriteTask(CopyOnWriteArrayList<String> list, int index) {
			this.list = list;
			this.index = index;
		}

		@Override
		public void run() {
			list.remove(index);
			list.add(index, "write_" + index);
		}
	}

	public void run() {
		final int NUMBER = 10;
		CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<String>();
		for (int i = 0; i < NUMBER; i++) {
			list.add("main_" + i);
		}
		// 线程缓冲池
		ExecutorService service = Executors.newFixedThreadPool(NUMBER);
		for (int i = 0; i < NUMBER; i++) {
			service.execute(new ReadTask(list));
			service.execute(new WriteTask(list, i));
		}
		service.shutdown();
	}

	private static void test() {
		List<String> datas = new ArrayList<>();
		for (int i = 0; i < 10; i++) {
			datas.add("Word_" + i);
		}
		// 迭代器
		Iterator<String> iterator = datas.iterator();
		while (iterator.hasNext()) {
			System.out.println(iterator.next());
		}

	}

}
